from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from users.models import User

import re

from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from django.conf import settings

from rest_framework_jwt.settings import api_settings

class OauthSerializers(serializers.ModelSerializer):

    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    access_token = serializers.CharField(write_only=True)
    # 重写操作
    mobile = serializers.CharField(max_length=11,min_length=11)

    token = serializers.CharField(read_only=True)
    username = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('mobile','password','access_token','sms_code','token','username')
        extra_kwargs = {
            'password':{
                'max_length':20,
                'min_length':8,
                'write_only':True,
            }
        }

    # 手机号验证
    def validate_mobile(self,value):
        if not re.match(r'1[3-9]\d{9}$',value):
            return serializers.ValidationError('手机号格式错误')
        return value

    def validate(self, attrs):

        # 验证码判断
        redis_coon = get_redis_connection('verify')
        mobile = attrs['mobile']
        real_sms_code = redis_coon.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        # access_token 判断
        tjs = TJS(settings.SECRET_KEY,300)
        # 解密 access_token
        try:
            data = tjs.loads(attrs['access_token'])
        except:
            raise serializers.ValidationError('错误的access_token')

        # 获取openid
        openid = data.get('openid')
        if openid is None:
            raise serializers.ValidationError('openid已经失效')

        attrs['openid'] = openid

        # 查询用户
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except:
            return attrs
        else:
            # 用户存在
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user

        return attrs


    def create(self, validated_data):

        # 判断是否有user
        user = validated_data.get('user')
        if user is None:
            user = User.objects.create_user(username=validated_data['mobile'],password=validated_data['password'],
                                     mobile=validated_data['mobile'])
        # 绑定openid
        OAuthQQUser.objects.create(user=user, openid=validated_data['openid'])

        # 生成jwk token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token

        return user
